/**
 *  @(#)  IFAAAuthenticator  module    1.0  2017/03/24
 *
 *  Copyright  (c)  2017,  IFAA  and/or  its  affiliates.  All  rights  reserved.
 *
 *  Redistribution  and  use  in  source  and  binary  forms,  with  or  without
 *  modification,  are  permitted  provided  that  the  following  conditions  are  met:
 *
 *  -Redistribution  of  source  code  must  retain  the  above  copyright  notice,  this
 *    list  of  conditions  and  the  following  disclaimer.
 *
 *  -Redistribution  in  binary  form  must  reproduce  the  above  copyright  notice,
 *    this  list  of  conditions  and  the  following  disclaimer  in  the  documentation
 *    and/or  other  materials  provided  with  the  distribution.
 *
 *  Neither  the  name  of  IFAA  or  the  names  of  contributors  may
 *  be  used  to  endorse  or  promote  products  derived  from  this  software  without
 *  specific  prior  written  permission.
 *
 *  This  software  is  provided  "AS  IS,"  without  a  warranty  of  any  kind.  ALL
 *  EXPRESS  OR  IMPLIED  CONDITIONS,  REPRESENTATIONS  AND  WARRANTIES,  INCLUDING
 *  ANY  IMPLIED  WARRANTY  OF  MERCHANTABILITY,  FITNESS  FOR  A  PARTICULAR  PURPOSE
 *  OR  NON-INFRINGEMENT,  ARE  HEREBY  EXCLUDED.  IFAA,  ORG.
 *  AND  ITS  LICENSORS  SHALL  NOT  BE  LIABLE  FOR  ANY  DAMAGES  SUFFERED  BY  LICENSEE
 *  AS  A  RESULT  OF  USING,  MODIFYING  OR  DISTRIBUTING  THIS  SOFTWARE  OR  ITS
 *  DERIVATIVES.  IN  NO  EVENT  WILL  IFAA  OR  ITS  LICENSORS  BE  LIABLE  FOR  ANY  LOST
 *  REVENUE,  PROFIT  OR  DATA,  OR  FOR  DIRECT,  INDIRECT,  SPECIAL,  CONSEQUENTIAL,
 *  INCIDENTAL  OR  PUNITIVE  DAMAGES,  HOWEVER  CAUSED  AND  REGARDLESS  OF  THE  THEORY
 *  OF  LIABILITY,  ARISING  OUT  OF  THE  USE  OF  OR  INABILITY  TO  USE  THIS  SOFTWARE,
 *  EVEN  IF  IFAA  HAS  BEEN  ADVISED  OF  THE  POSSIBILITY  OF  SUCH  DAMAGES.
 *
 *  You  acknowledge  that  this  software  is  not  designed,  licensed  or  intended
 *  for  use  in  the  design,  construction,  operation  or  maintenance  of  any
 *  nuclear  facility.
 *
 */
package com.ifaa.sdk.api;

import java.util.ArrayList;
import java.util.List;

import android.content.Context;

import com.ifaa.sdk.auth.AuthInfo;
import com.ifaa.sdk.auth.AuthenticatorFactory;
import com.ifaa.sdk.auth.AuthenticatorLOG;
import com.ifaa.sdk.auth.IAuthenticator;
import com.ifaa.sdk.authenticatorservice.fingerprint.util.FingerprintDataUtil;
import com.ifaa.sdk.util.CommonUtils;

/**
 * authenticator manager
 */
public class AuthenticatorManager{


    /**
     * 检测设备是否支持指定类型的IFAA协议功能
     * @param context
     * @param authType 认证类型，见定义Constants,目前定义了指纹类型：TYPE_FINGERPRINT
     * @return ture 表示支持该认证类型，否则不支持
     */
    public synchronized static boolean isSupportIFAA(Context context, int authType) {
        context = context.getApplicationContext();
        IAuthenticator authenticator = AuthenticatorFactory.create(context, authType);
        if (authenticator == null) {
            return false;
        }

        return authenticator.isSupported();
    }

    /**
     * 获取指定认证类型的auth model 数据
     * @param context
     * @param authType
     * @param wearableType
     * @param token
     * @return 返回BICDataModel对象
     */
    private synchronized static BICDataModel getAuthModelByAuthType(Context context, int authType,
                                                       int wearableType, String token) {
        context = context.getApplicationContext();

        try {

            if (!isSupportIFAA(context, authType)) {
                return null;
            }
            IAuthenticator authenticator = AuthenticatorFactory.create(context, authType);
            if (authenticator == null) {
                return null;
            }

            AuthInfo info = authenticator.getAuthInfo();

            String deviceId = authenticator.getDeviceId();

            int userStatus = AuthenticatorConstants.CLIENT_STATUS_OPEN;
            if (!CommonUtils.isBlank(token)) {
                userStatus = authenticator.checkUserStatus(token);
            }

            int serviceVersion = 6;
            BICDataModel model = new BICDataModel(userStatus, info.getType(), wearableType,
                    info.getProtocolType(), info.getProtocolVersion(), info.getVendor(),
                    serviceVersion, deviceId, info.getPhoneModle(), info.getDeviceModel());
            return model;
        } catch (Exception e) {
            return null;
        }
    }

    /**
     * 获取设备的认证数据，主要将设备相关的信息上传的服务端，服务端通过该信息来生成对应的指令请求
     * @param context
     * @param token 用户关联的token
     * @return 返回认证数据json格式，获取不到为空字符串
     */
    public synchronized static String getAuthData(Context context,
                                        String token) {
            AuthenticatorLOG.fpInfo("getAuthData enter [token:" + token + "]");
            long enterTime = System.currentTimeMillis();

            context = context.getApplicationContext();

            List<BICDataModel> models = new ArrayList<BICDataModel>();

            // fingerprint
            BICDataModel model = getAuthModelByAuthType(context,
                AuthenticatorConstants.AUTHTYPE_FINGERPRINT, 0, token);
            if (model != null) {
                models.add(model);
            }


            String result = BICDataUtil.toDataJson(models, context);
            AuthenticatorLOG.fpInfo("getAuthData exit [result:" + result + "] [timecost:"
                                    + (System.currentTimeMillis() - enterTime) + "]");

            return result;
    }

    /**
     * 创建一个认证对象
     * 
     * @param context
     * @param type 认证类型，见定义Constants,目前定义了指纹类型：TYPE_FINGERPRINT
     * @return 返回一个认证对象，null表示创建失败
     */
    public synchronized static IAuthenticator create(Context context, int type, String appname) {
        context = context.getApplicationContext();
        if (appname == null || appname.isEmpty()) {
          return null;
        }
        FingerprintDataUtil.appname = appname;
        return AuthenticatorFactory.create(context, type);
}



}
